import React, { Component } from 'react';
import { DragDropContext } from 'react-dnd';
import update from 'immutability-helper';
import HTML5Backend from 'react-dnd-html5-backend';
import OneLevelItem from './OneLevelItem';
import TwoLevelItem  from './TwoLevelItem';

const style = {
  padding: 80,
  display: 'flex'
}
@DragDropContext(HTML5Backend)
export default class TwoDnDDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      oneLevelList: [{
        id: 1,
        name: 'oneLevel1',
      }, {
        id: 2,
        name: 'oneLevel2'
      }, {
        id: 3,
        name: 'oneLevel3'
      }, {
        id: 4,
        name: 'oneLevel4'
      }],
      twoLevelList: []
    }
  }
  moveAction = (dragIndex, hoverIndex, flag, lastId) => {
    const { oneLevelList, twoLevelList } = this.state;
    if (flag === 'oneLevel') {
      const dragOneLevelItem = oneLevelList[dragIndex];
      this.setState(
        update(this.state, {
          oneLevelList: {
            $splice: [[dragIndex, 1], [hoverIndex, 0, dragOneLevelItem]],
          }
        })
      )
      return;
    }
    const dragTwoLevelItem = twoLevelList[dragIndex];
    this.setState(
      update(this.state, {
        twoLevelList: {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragTwoLevelItem]],
        }
      }), () => {
        localStorage.setItem(lastId, JSON.stringify(this.state.twoLevelList));
      }
    )
  }
  clickAction = (id) => {
    const getTwoLevelList = JSON.parse(localStorage.getItem(id));
    if (getTwoLevelList && getTwoLevelList.length > 0) {
      this.setState({
        twoLevelList: getTwoLevelList
      })
      return;
    }
    const arr = [];
    for (let i = 0; i < id; i++) {
      arr.push({
        id: `${id}${i}`,
        name: `twoLevel${id}${i}`,
        lastId: id
      })
    }
    this.setState({
      twoLevelList: arr
    })
  }
  render() {
    const { oneLevelList, twoLevelList } = this.state;
    return (
      <div style={{ ...style }}>
        <div style={{ width: 150 }}>
          <p>第一级</p>
          {
            oneLevelList.map((item, index) => (
              <OneLevelItem
                key={item.id}
                index={index}
                id={item.id}
                name={item.name}
                moveAction={this.moveAction}
                clickAction={this.clickAction}
              />
            ))
          }
        </div>
        <div style={{ marginLeft: 50 }}>
          <p>第二级</p>
          {
            twoLevelList.length > 0 ? twoLevelList.map((item, index) => (
              <TwoLevelItem
                key={item.id}
                index={index}
                lastId={item.lastId}
                id={item.id}
                name={item.name}
                moveAction={this.moveAction}
              />
            )) : '暂无数据'
          }
        </div>
      </div>
    )
  }
}
